﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;

namespace Wordpress.Phone
{
    public partial class MainPage : PhoneApplicationPage
    {
        protected MainViewModel viewModel;
        
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (this.viewModel == null) {
                // Set the data context of the listbox control to the sample data
                this.viewModel = new MainViewModel();
                DataContext = this.viewModel;
            }

            // Load data for the ViewModel Items
            this.viewModel.LoadMovies();
        }

        // Handle selection changed on ListBox
        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (MainListBox.SelectedIndex == -1)
                return;

            // Navigate to the new page
            NavigationService.Navigate(new Uri("/Views/DetailPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));

            // Reset selected index to -1 (no selection)
            MainListBox.SelectedIndex = -1;
        }

        private void LastSynchroElement_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            viewModel.UpdateMovies();
        }

        private void Thumbnail_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            Image img = sender as Image;
            img.Source = new BitmapImage(new Uri("/Wordpress.Phone;component/Assets/Images/Thumbnail.png", UriKind.Relative));
        }
    }
}